package ru.ifmo.network;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author avhaliullin
 */
public class Requester {
    private static final Logger log = Logger.getLogger(Requester.class.getName());

    private static Socket connect(String address, int port) throws IOException {
        return new Socket(address, port);
    }

    public static List<String> listFiles(String address, int port) {
        Socket socket = null;
        try {
            socket = connect(address, port);
            DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

            outputStream.writeUTF("LIST");
            outputStream.flush();

            int count = inputStream.readInt();
            List<String> filesList = new ArrayList<String>();
            for (int i = 0; i < count; i++) {
                filesList.add(inputStream.readUTF());
            }
            return filesList;
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error ", e);
            return new ArrayList<String>();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    }

    public static FiniteInputStreamHolder getFile(String address, int port, String fileName) {
        Socket socket = null;
        try {
            socket = connect(address, port);
            final DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

            outputStream.writeUTF("GET");
            outputStream.writeUTF(fileName);
            outputStream.flush();

            final long length = inputStream.readLong();
            return new FiniteInputStreamHolder(inputStream, length);
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error ", e);
            return null;
        }
    }
}
